const axios  =  require("axios").default
const cheerio = require("cheerio")
const Book = require('../model/book')
const fs = require("fs");
const path = require("path");
  



let bookDetails = [];
let bookAllDetailsLink = {};
//最开始运行
// getBookType().then((bookType)=>{
   
//     getAllTypeDetailsLink(bookType);

//    setTimeout(() => {
    
//        fs.writeFileSync("./boolAlllink.txt",JSON.stringify(booKAllDetailsLink));
      
//    }, 4000);
   
// });

//获取网页
async function getHTML(n="全部"){
   // https://book.douban.com/latest?subcat=%E6%96%87%E5%AD%A6
   let result = await axios.get("https://book.douban.com/latest",{
        params: {
            subcat: n
        },
    });
return result.data
   
}
//getHTML().then()
//本地读取文件
function getLocalFile(file){
   const a =fs.readFileSync(path.resolve(__dirname,file),"UTF-8");
   return a;
}
  function delay(n=2500){
    let now = new Date();
   while(( new Date() - now)<n){
        
   }
  }
 //获取书籍详细页面链接
async function getDetailsLinks(type = "全部"){
    const html =  await  getHTML(type);
    const $ = cheerio.load(html); 
    const elements = $("#content .grid-16-8 .chart-dashed-list .media .media__img a")
    const links =  elements.map((i,e)=>{
          const h  = e.attribs["href"];
          return h ;    
     }).get();
    delay();
    return links;
}

async function getDetailsHTML(url){
     const result = (await axios.get(url)); 
      return result.data;
}

//获取书籍分类标签
async function getBookType(){
    const html =  await  getHTML();
    const $ = cheerio.load(html); 
    const elemntsA =  $("#content .grid-16-8 .article .xbar div a");
    const typeNames = elemntsA.map((i,ele)=>{
         return ele.children[0].data
    }).get();
   
    return typeNames;
}
//获取书籍详情生成书籍对象
async function getBookdetails(type = "文学",url){ 
    const ele = await getDetailsHTML(url);
    const $ = cheerio.load(ele);
    const bookName = $("#wrapper h1 span").text();//#content .grid-16-8 .article .indent .subjectwrap
    const imgUrl = $("#mainpic a img").attr('src');//图片链接
    let author,oBookName=null,press,birthday,subtitle,product,ISBN,price,pageNumber,tarnslator,dreUp;
    const infos = $("#info .pl");
    for(var i =0;i<infos.length;i++){
        switch((infos[i].childNodes[0].data).trim()){
            case "作者" :  
                   author =  infos[i].next.next.children[0].data; 
                     break;
            case "出版社:":
                     press = setBookInfo(infos[i]).trim();
                     break;
            case "出品方:":
                    product = infos[i].next.next.children[0].data;
                     break;
            case "原作名:":
                    oBookName = setBookInfo(infos[i]).trim();
                     break;
            case "副标题:":
                    subtitle = setBookInfo(infos[i]).trim();
                     break;
            case "译者":
                     tarnslator = infos[i].next.next.children[0].data;
                     break;
            case "出版年:":
                    birthday = setBookInfo(infos[i]).trim();
                     break;          
            case "页数:":
                    pageNumber = setBookInfo(infos[i]).trim();
                     break;
            case "定价:":
                     price = setBookInfo(infos[i]).trim();
                     break;
            case "装帧:":
                     dreUp = setBookInfo(infos[i]).trim();
                     break;
            case "丛书:":
                    series = infos[i].next.next.children[0].data;
                     break;
             case "ISBN:":
                     ISBN = setBookInfo(infos[i]).trim();
                     break;
            
        }
    }
   
      
 
     return {
        bookName,
        oBookName,
        imgUrl,
        author,
        press,
        birthday,
        subtitle,
        product,
        ISBN,
        price,
        pageNumber,
        tarnslator,
        type,
        dreUp
     } //childNodes[0].data;
}
function setBookInfo(ele){
    return ele.next.data

}


async function createAllBookdetails(){
    const allBookLinks =  JSON.parse(getLocalFile("./boolAlllink.txt"));

      allBookLinks["文学"].map((link)=>{
          setTimeout(() => {
            getBookdetails(type,link).then((obj)=>{
                bookDetails.push(obj);
              })
          }, 1000);
        
      })
  


}
//获取所有分类的详细链接
async function allTypeLinks(){
    const types = await getBookType()
   for(let i=0;i<types.length;i++){
    bookAllDetailsLink[types[i]] = await getDetailsLinks(types[i])
   }
   // console.log(bookAllDetailsLink);
   return bookAllDetailsLink;
};

(async function(){
   // const allLinks =  await allTypeLinks();
    //const t = await getBookdetails("文学","https://book.douban.com/subject/35544870/");
   const localLink =JSON.parse(fs.readFileSync("./boolAlllink.txt",'utf-8'));
   
   for(var type in localLink){
     for(let i=0;i<localLink[type].length;i++){
          delay();
         const temp = await getBookdetails(type,localLink[type][i])
         Book.create(temp);
     }
   }

    
})();


//createAllBookdetails();


